"""
邮件管理API端点
"""

from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query, BackgroundTasks
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.core.logging import get_logger
from app.api.deps import get_current_active_user
from app.models.user import User
from app.services.email_service import EmailService
from app.schemas.email import (
    EmailSendRequest, EmailTemplateRequest, EmailBatchRequest, UserMessageRequest,
    EmailSendResponse, EmailBatchResponse, EmailMessageResponse, EmailMessageDetail,
    EmailStatsResponse, EmailListParams, EmailTemplateCreate, EmailTemplateUpdate,
    EmailTemplateResponse
)
from app.middleware.exception_middleware import BusinessException, ResourceNotFoundException

logger = get_logger(__name__)
router = APIRouter(prefix="/email", tags=["📧 邮件系统"])


def get_email_service(db: Session = Depends(get_db)) -> EmailService:
    """获取邮件服务实例"""
    return EmailService(db)


@router.post("/send", response_model=EmailSendResponse)
async def send_email(
    request: EmailSendRequest,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_active_user),
    email_service: EmailService = Depends(get_email_service)
):
    """
    发送邮件
    
    - **recipient_email**: 收件人邮箱
    - **subject**: 邮件主题
    - **body_text**: 纯文本内容（可选）
    - **body_html**: HTML内容（可选）
    - **priority**: 邮件优先级
    """
    try:
        # 在后台任务中发送邮件以提高响应速度
        def send_email_task():
            email_message = email_service.send_email(request, current_user)
            return email_message
        
        background_tasks.add_task(send_email_task)
        
        return EmailSendResponse(
            success=True,
            message="邮件已加入发送队列",
            request_id=getattr(request, 'request_id', None)
        )
        
    except Exception as e:
        logger.error(f"发送邮件失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"发送邮件失败: {str(e)}"
        )


@router.post("/send-template", response_model=EmailSendResponse)
async def send_template_email(
    request: EmailTemplateRequest,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_active_user),
    email_service: EmailService = Depends(get_email_service)
):
    """
    使用模板发送邮件
    
    - **recipient_email**: 收件人邮箱
    - **template_name**: 模板名称
    - **template_data**: 模板数据
    - **priority**: 邮件优先级
    """
    try:
        def send_template_email_task():
            return email_service.send_template_email(request, current_user)
        
        background_tasks.add_task(send_template_email_task)
        
        return EmailSendResponse(
            success=True,
            message="模板邮件已加入发送队列"
        )
        
    except Exception as e:
        logger.error(f"发送模板邮件失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"发送模板邮件失败: {str(e)}"
        )


@router.post("/send-user-message", response_model=EmailSendResponse)
async def send_user_message(
    request: UserMessageRequest,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_active_user),
    email_service: EmailService = Depends(get_email_service)
):
    """
    发送用户间消息
    
    - **recipient_id**: 收件人用户ID
    - **subject**: 消息主题
    - **message**: 消息内容
    - **priority**: 消息优先级
    """
    try:
        def send_user_message_task():
            return email_service.send_user_message(request, current_user)
        
        background_tasks.add_task(send_user_message_task)
        
        return EmailSendResponse(
            success=True,
            message="用户消息已发送"
        )
        
    except Exception as e:
        logger.error(f"发送用户消息失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"发送用户消息失败: {str(e)}"
        )


@router.post("/send-batch", response_model=EmailBatchResponse)
async def send_batch_emails(
    request: EmailBatchRequest,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_active_user),
    email_service: EmailService = Depends(get_email_service)
):
    """
    批量发送邮件
    
    - **recipients**: 收件人列表
    - **subject**: 邮件主题
    - **body_text**: 纯文本内容（可选）
    - **body_html**: HTML内容（可选）
    - **template_name**: 模板名称（可选）
    - **scheduled_at**: 计划发送时间（可选）
    """
    try:
        def send_batch_emails_task():
            return email_service.send_batch_emails(request, current_user)
        
        background_tasks.add_task(send_batch_emails_task)
        
        return EmailBatchResponse(
            success=True,
            message="批量邮件已加入发送队列",
            batch_id="pending",
            total_emails=len(request.recipients),
            queued_emails=len(request.recipients),
            failed_emails=0,
            email_ids=[]
        )
        
    except Exception as e:
        logger.error(f"批量发送邮件失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"批量发送邮件失败: {str(e)}"
        )


@router.get("/list", response_model=List[EmailMessageResponse])
async def get_email_list(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页大小"),
    status: Optional[str] = Query(None, description="邮件状态"),
    email_type: Optional[str] = Query(None, description="邮件类型"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    current_user: User = Depends(get_current_active_user),
    email_service: EmailService = Depends(get_email_service)
):
    """
    获取邮件列表
    
    支持分页、过滤和搜索功能
    """
    try:
        params = EmailListParams(
            page=page,
            size=size,
            status=status,
            email_type=email_type,
            search=search
        )
        
        result = email_service.get_email_list(params, current_user.id)
        return result.items
        
    except Exception as e:
        logger.error(f"获取邮件列表失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取邮件列表失败: {str(e)}"
        )


@router.get("/{email_id}", response_model=EmailMessageDetail)
async def get_email_detail(
    email_id: int,
    current_user: User = Depends(get_current_active_user),
    email_service: EmailService = Depends(get_email_service)
):
    """
    获取邮件详情
    
    - **email_id**: 邮件ID
    """
    try:
        email_message = email_service.get_email_by_id(email_id, current_user.id)
        if not email_message:
            raise ResourceNotFoundException("邮件不存在或无权限访问")
        
        return email_message
        
    except ResourceNotFoundException:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="邮件不存在或无权限访问"
        )
    except Exception as e:
        logger.error(f"获取邮件详情失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取邮件详情失败: {str(e)}"
        )


@router.post("/{email_id}/retry", response_model=EmailSendResponse)
async def retry_email(
    email_id: int,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_active_user),
    email_service: EmailService = Depends(get_email_service)
):
    """
    重试发送失败的邮件
    
    - **email_id**: 邮件ID
    """
    try:
        def retry_email_task():
            return email_service.retry_failed_email(email_id)
        
        background_tasks.add_task(retry_email_task)
        
        return EmailSendResponse(
            success=True,
            message="邮件重试发送已加入队列",
            email_id=email_id
        )
        
    except Exception as e:
        logger.error(f"重试发送邮件失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"重试发送邮件失败: {str(e)}"
        )


@router.post("/{email_id}/mark-read", response_model=EmailMessageResponse)
async def mark_email_as_read(
    email_id: int,
    current_user: User = Depends(get_current_active_user),
    email_service: EmailService = Depends(get_email_service)
):
    """
    标记邮件为已读
    
    - **email_id**: 邮件ID
    """
    try:
        email_message = email_service.mark_email_as_read(email_id, current_user.id)
        return email_message
        
    except ResourceNotFoundException:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="邮件不存在或无权限"
        )
    except Exception as e:
        logger.error(f"标记邮件已读失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"标记邮件已读失败: {str(e)}"
        )


@router.get("/stats/overview", response_model=EmailStatsResponse)
async def get_email_stats(
    days: int = Query(30, ge=1, le=365, description="统计天数"),
    current_user: User = Depends(get_current_active_user),
    email_service: EmailService = Depends(get_email_service)
):
    """
    获取邮件统计信息
    
    - **days**: 统计天数（默认30天）
    """
    try:
        stats = email_service.get_email_stats(current_user.id, days)
        return EmailStatsResponse(**stats)
        
    except Exception as e:
        logger.error(f"获取邮件统计失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取邮件统计失败: {str(e)}"
        )


# 邮件模板管理API
@router.post("/templates", response_model=EmailTemplateResponse)
async def create_email_template(
    request: EmailTemplateCreate,
    current_user: User = Depends(get_current_active_user),
    email_service: EmailService = Depends(get_email_service)
):
    """
    创建邮件模板
    
    需要管理员权限
    """
    try:
        # 检查权限（这里简化处理，实际应该检查具体权限）
        if not current_user.is_superuser:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="权限不足，需要管理员权限"
            )
        
        template = email_service.create_template(request)
        return template
        
    except BusinessException as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"创建邮件模板失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建邮件模板失败: {str(e)}"
        )


@router.get("/templates", response_model=List[EmailTemplateResponse])
async def get_email_templates(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页大小"),
    current_user: User = Depends(get_current_active_user),
    email_service: EmailService = Depends(get_email_service)
):
    """
    获取邮件模板列表
    """
    try:
        result = email_service.get_templates_list(page, size)
        return result.items
        
    except Exception as e:
        logger.error(f"获取邮件模板列表失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取邮件模板列表失败: {str(e)}"
        )


@router.put("/templates/{template_id}", response_model=EmailTemplateResponse)
async def update_email_template(
    template_id: int,
    request: EmailTemplateUpdate,
    current_user: User = Depends(get_current_active_user),
    email_service: EmailService = Depends(get_email_service)
):
    """
    更新邮件模板
    
    需要管理员权限
    """
    try:
        if not current_user.is_superuser:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="权限不足，需要管理员权限"
            )
        
        template = email_service.update_template(template_id, request)
        return template
        
    except ResourceNotFoundException:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="邮件模板不存在"
        )
    except BusinessException as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"更新邮件模板失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新邮件模板失败: {str(e)}"
        )


@router.delete("/templates/{template_id}")
async def delete_email_template(
    template_id: int,
    current_user: User = Depends(get_current_active_user),
    email_service: EmailService = Depends(get_email_service)
):
    """
    删除邮件模板
    
    需要管理员权限
    """
    try:
        if not current_user.is_superuser:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="权限不足，需要管理员权限"
            )
        
        email_service.delete_template(template_id)
        return {"message": "邮件模板删除成功"}
        
    except ResourceNotFoundException:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="邮件模板不存在"
        )
    except BusinessException as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"删除邮件模板失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除邮件模板失败: {str(e)}"
        )